- By default c++ pass by value. i.e. values are copied to function parameters.
-
Pass by value just copies the data to parameter variable: look at code below
#include<iostream> void change_var(int a) { a++; } int main() { int x=20; change_var(x); std::cout<<x; //here value 20 is copied in parameter a and is incremented. the changes will be only made in parameter 'a' and not in variable 'x', it will generate output as : 21 20 return 0; }
- pass by reference will change the data globally just like pass by pointer.
#include<iostream> void change_var(int &a) //here a is an reference to variable 'x' { a++; } int main() { int x=20; std::cout<<x<<std::endl; //will print 20 change_var(x); std::cout<<x<<std::endl; //will print 21 return 0; }
- Pass by pointers will also change the data globally. It is suggested to use pass by reference over pointers.
-
have a look at the code:
#include<iostream> int * change_var(int *a) //here a is an pointer to variable 'x' and a stores memory address of varialbe x. { (*a)++; //we need to dereference the pointer to access its value. 'a' holds the address and *a has its value. note that *a++ won't work and it will increase the value of address by one. *a++; //trying to increase value of a, but in fact it increases pointer value. It is same as saying a++. return a; } int main() { int x=20; std::cout<<"address of x is "<<&x<<std::endl; int *a=change_var(&x); std::cout<<x<<std::endl; //here value 20 is in x, and x is referenced by parameter/alias 'a'. the changes will be made in parameter 'a' and in variable 'x', it will generate output as : 21 std::cout<<"address after calling function is "<<a; }
Output
address of x is 0x7ffcd5f30234
21
address after calling function is 0x7ffcd5f30238
Note that the address increase by 4, since now pointer points to next memory which is 4 blocks away (integer takes 4 bytes).